<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        title="注意: 只允许为第三级分类设置相关参数!"
        type="warning"
        show-icon
      ></el-alert>
      <!-- 级联选择器分类参数列表 -->
      <el-row>
        <el-col class="goodsCate">
          <span>选择商品分类：</span>
          <!-- //级联选择器 -->
          <el-cascader
            v-model="selectValue"
            :options="cateList"
            :props="CateProps"
            @change="selectHandleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- Tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="selectHandleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            class="addparams"
            type="primary"
            size="mini"
            :disabled="isSelectThree"
            @click="addParamsDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model.trim="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="findParamById(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            class="addparams"
            type="primary"
            size="mini"
            :disabled="isSelectThree"
            @click="addParamsDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(i, scope.row)"
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model.trim="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="静态属性"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="findParamById(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParamsById(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性对话框 -->
    <el-dialog
      :title="activeName === 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogClose"
    >
      <el-form
        :model="addParamsRuleForm"
        :rules="addParamsRules"
        ref="addParamsForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addParamsRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改属性对话框 -->
    <el-dialog
      :title="activeName === 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editParamsDialogVisible"
      width="50%"
    >
      <el-form
        :model="addParamsRuleForm"
        :rules="addParamsRules"
        ref="addParamsForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          :label="activeName === 'many' ? '动态参数' : '静态属性'"
          prop="attr_name"
        >
          <el-input v-model="addParamsRuleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Params",
  data() {
    return {
      inputValue: "", //文本框输入绑定的值
      inputVisible: false, //控制文本框的显示与隐藏
      editParamsDialogVisible: false, //控制修改属性对话框的显示与隐藏
      addParamsDialogVisible: false, //控制添加属性对话框的显示与隐藏
      cateList: [], //所有分类列表
      selectValue: [], //级联选择的值
      CateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeName: "many", //默认激活的属性
      manyTableData: [], //动态属性数据
      onlyTableData: [], //静态属性数据
      //绑定的数据
      addParamsRuleForm: {
        attr_name: "",
      },
      //验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: "请输入添加的参数", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateList();
  },

  methods: {
    //获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status == 200) {
        this.cateList = res.data;
        this.$message.success("获取分类列表成功");
      } else {
        this.$message.error("获取分类列表失败");
      }
    },

    //级联选择器的值发生改变时调用该函数
    selectHandleChange() {
      console.log(this.selectValue);
      this.getParamsList();
    },
    //选择的参数发生改变时调用该函数
    selectHandleClick() {
      this.getParamsList();
    },

    //获取参数列表
    async getParamsList() {
      const { data: res } = await this.$http.get(
        `categories/${this.selectValue[2]}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      if (res.meta.status == 200) {
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          //控制文本框显示与隐藏
          item.inputVisible = false;
          //文本框输入的值
          item.inputValue = "";
        });
        if (this.activeName === "many") {
          this.manyTableData = res.data; //j静态数据
        } else {
          this.onlyTableData = res.data; //动态数据
        }
        this.$message.success("获取参数列表成功");
      } else {
        if (this.selectValue.length != 3) {
          this.$message.warning("请选择商品分类");
        } else {
          this.$message.error("获取参数列表失败");
        }
      }
    },

    //预校验后，点击确定添加参数
    addParams() {
      this.$refs.addParamsForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post(
            `categories/${
              this.selectValue[this.selectValue.length - 1]
            }/attributes`,
            {
              attr_name: this.addParamsRuleForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.meta.status == 201) {
            this.$message.success("添加参数成功");
            this.getParamsList();
            this.addParamsDialogVisible = false;
          } else {
            this.$message.error("添加参数失败");
          }
        } else {
          return;
        }
      });
    },

    //添加对话框关闭后触发表单重置
    addParamsDialogClose() {
      this.$refs.addParamsForm.resetFields();
    },

    // 根据 ID 查询参数
    async findParamById(id) {
      this.editParamsDialogVisible = true;
      const { data: res } = await this.$http.get(
        `categories/${
          this.selectValue[this.selectValue.length - 1]
        }/attributes/${id}`
      );
      if (res.meta.status == 200) {
        this.addParamsRuleForm = res.data;
      } else {
        return;
      }
    },

    //点击确定，预校验后完成修改
    editParams() {
      this.$refs.addParamsForm.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/${
              this.selectValue[this.selectValue.length - 1]
            }/attributes/${this.addParamsRuleForm.attr_id}`,
            {
              attr_name: this.addParamsRuleForm.attr_name,
              attr_sel: this.activeName,
            }
          );
          if (res.meta.status == 200) {
            this.$message.success("修改参数成功");
            this.getParamsList();
            this.editParamsDialogVisible = false;
          } else {
            this.$message.error("修改参数失败");
          }
        } else {
          return;
        }
      });
    },

    //删除参数
    async deleteParamsById(id) {
      const val = await this.$confirm(
        "此操作将永久删除该参数, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (val == "confirm") {
        const { data: res } = await this.$http.delete(
          `categories/${
            this.selectValue[this.selectValue.length - 1]
          }/attributes/${id}`
        );
        if (res.meta.status == 200) {
          this.$message.success("成功删除该参数");
          this.getParamsList();
        } else {
          console.log(res.data);
          this.$message.error("参数删除失败");
        }
      } else {
        this.$message.info("已取消删除");
      }
    },

    //按下enter或鼠标失去焦点时触发函数
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }

      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.saveArrtVals(row);
    },
    //点击时显示文本框
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    // 修改参数项
    async saveArrtVals(row) {
      const { data: res } = await this.$http.put(
        `categories/${
          this.selectValue[this.selectValue.length - 1]
        }/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(" "),
        }
      );
      if (res.meta.status == 200) {
        this.$message.success("修改参数项成功");
      } else {
        this.$message.error("修改参数项失败");
      }
    },

    // 删除对应参数可选项
    handleClose(i, row) {
      row.attr_vals.splice(i, 1);
      this.saveArrtVals(row);
    },
  },

  computed: {
    //是否选择第三级分类列表
    isSelectThree() {
      if (this.selectValue.length === 3) {
        return false;
      } else {
        //如果没有选择三级分类，强制赋值为空
        this.selectValue = []; 
        this.manyTableData=[]
        this.onlyTableData=[]
        return true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.goodsCate {
  margin: 15px 0;
}

.addparams {
  margin-bottom: 15px;
}
.el-tag {
  margin: 10px 20px;
}

.input-new-tag {
  width: 160px;
}

.button-new-tag {
  margin-left: 20px;
}
</style>